/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.common.web.Util;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.scene.bean.CalibrationView;
import com.koron.scene.domain.*;
import com.koron.scene.mapper.DeviceCalibrationMapper;
import com.koron.scene.mapper.DeviceMapper;
import com.koron.scene.service.api.DeviceCalibrationService;
import com.koron.scene.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;
import java.util.stream.Collectors;

@Service
@PropertySource({"classpath:deviceCheckFlow.properties"})
public class DeviceCalibrationServiceImpl implements DeviceCalibrationService, AfterApprovalService, InitializingBean {

    private final static  Logger logger = LoggerFactory.getLogger(DeviceCalibrationServiceImpl.class);

    // 状态:0-草稿 1-审批中 2-审批通过
    private Integer STATUS_0 = 0;
    private Integer STATUS_1 = 1;
    private Integer STATUS_2 = 2;

    @Value("${device_calibration}")
    private String templateKey;

    @Value("${flow.scene.setCode}")
    private String setCode;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private Util util;

    @Override
    public DataBean<DeviceCalibration> fetchCalibrations(String corpCode, String title, String responsibleEmployeeName, String calibrationCorp, Integer status, Integer start, Integer rows,String keyword) {
        if (logger.isDebugEnabled()) {
            logger.debug("responsibleEmployeeName = {}, calibrationCorp = {}, status = {}", responsibleEmployeeName, calibrationCorp, status);
        }
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCalibrationMapper mapper = factory.getMapper(DeviceCalibrationMapper.class);
            String codes = util.getCodes(corpCode);
            List<DeviceCalibration> calibrations = mapper.queryByCondition(codes, title, responsibleEmployeeName, calibrationCorp, status, start, rows,keyword);
            Integer total = mapper.countByCondition(codes, title, responsibleEmployeeName, calibrationCorp, status,keyword);
            if (calibrations != null && !calibrations.isEmpty()) {
                calibrations.forEach(dc -> {
                    CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(dc.getCorpCode());
                    if (corpBean != null) {
                        dc.setCorpName(corpBean.getCorpName());
                    }
                });
            }
            DataBean<DeviceCalibration> dataBean = new DataBean<>();
            dataBean.setList(calibrations);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(total);
            dataBean.setTotalPage(total > rows ? (total % rows == 0 ? total / rows : total / rows + 1) : 1);
            dataBean.setPageNo(start / rows + 1);
            return dataBean;
        }
    }

    @Override
    public DeviceCalibration fetchOne(String id) {
        if (logger.isDebugEnabled()) {
            logger.debug("id = {}", id);
        }
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCalibration dc = factory.getMapper(DeviceCalibrationMapper.class).queryOne(id);
            if (dc != null && StringUtils.isNotBlank(dc.getCorpCode())) {
                CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(dc.getCorpCode());
                if (corpBean != null) {
                    dc.setCorpName(corpBean.getCorpName());
                }
            }
            return dc;
        }
    }


    @Override
    public Boolean batchDetele(List<String> idList) {
        try (SessionFactory factory = new SessionFactory()) {
//            return factory.getMapper(DeviceCalibrationMapper.class).batchDetele(idList) >= 0;
            Integer integer = factory.getMapper(DeviceCalibrationMapper.class).batchDetele(idList);
            if (integer > 0) {
                for (String deviceCalibrationId : idList) {
                    //检验记录删除成功后，删除检验与设备关系表中的该验检记录下的检查明细信息
                    factory.getMapper(DeviceMapper.class).deleteCalibrationRelation(deviceCalibrationId, null);
                }
                return true;
            }
            return false;
        }
    }

    @Override
    public MessageBean<String> persist(DeviceCalibration deviceCalibration) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), String.class);
        SessionFactory factory = new SessionFactory();
        try {
            Integer start = null, rows = null, status = null;
            String responsibleEmployeeName = null, calibrationCorp = null;
            DeviceCalibration dest = null;
            DeviceCalibrationMapper mapper = factory.getMapper(DeviceCalibrationMapper.class);
            List<DeviceCalibration> calibrations = mapper.queryAllByCondition(deviceCalibration.getCorpCode(), deviceCalibration.getTitle(), responsibleEmployeeName, calibrationCorp, status, start, rows);
            if (calibrations != null && !calibrations.isEmpty()) {
                calibrations = calibrations.stream().filter(c -> c.getTitle().equals(deviceCalibration.getTitle())).collect(Collectors.toList());
                dest = !calibrations.isEmpty() ? calibrations.get(0) : null;
            }

            if (StringUtils.isBlank(deviceCalibration.getId())) {
                if (dest != null) {
                    factory.close(false);
                    msg.setCode(BusinessCode.CALIBRATION_TITLE_DUP.getCode());
                    msg.setDescription(BusinessCode.CALIBRATION_TITLE_DUP.getDescription());
                    return msg;
                }
                deviceCalibration.setId(DefaultIdGenerator.getInstance().generateLongId());
                // 草稿
                deviceCalibration.setStatus(STATUS_0);
                if (mapper.insert(deviceCalibration) > 0) {

                    //检验记录保存成功后，将检查明细信息写入检验与设备关系表中
                    addCalibrationRelation(deviceCalibration, factory, mapper);

                    factory.close();
                    msg.setData(deviceCalibration.getId());
                    return msg;
                } else {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                    return msg;
                }
            } else {
                DeviceCalibration other = mapper.queryOne(deviceCalibration.getId());
                if (other == null) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("该检验记录已失效");
                    return msg;
                }
                deviceCalibration.setStatus(other.getStatus());
                if (deviceCalibration.getStatus() == STATUS_0) {
                    if (dest != null && !dest.getId().equals(deviceCalibration.getId())) {
                        factory.close(false);
                        msg.setCode(BusinessCode.CALIBRATION_TITLE_DUP.getCode());
                        msg.setDescription(BusinessCode.CALIBRATION_TITLE_DUP.getDescription());
                        return msg;
                    }
                    if (mapper.update(deviceCalibration) > 0) {

                        //检验记录保存成功后，将检查明细信息写入检验与设备关系表中
                        addCalibrationRelation(deviceCalibration, factory, mapper);

                        msg.setData(deviceCalibration.getId());
                        factory.close();
                        return msg;
                    }
                } else {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("只能修改处于草稿状态的检验记录");
                    return msg;
                }
                factory.close(false);
                msg.setCode(BusinessCode.CALIBRATION_CANNOT_UPDATE.getCode());
                msg.setDescription(BusinessCode.CALIBRATION_CANNOT_UPDATE.getDescription());
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
        factory.close(false);
        msg.setCode(BusinessCode.EXCEPTION.getCode());
        msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        return msg;
    }

    private void addCalibrationRelation(DeviceCalibration deviceCalibration, SessionFactory factory, DeviceCalibrationMapper mapper) {
        //根据水司code和检查负责人code查询检查明细信息
        List<CalibrationView> calibrationViews = factory.getMapper(DeviceMapper.class).queryForResponsibleEmployee(deviceCalibration.getCorpCode(), deviceCalibration.getResponsibleEmployeeCode(), null, null);
        //将检查明细信息写入检验与设备关系表中
        for (CalibrationView calibrationView : calibrationViews) {
            //写入前，先根据检验记录id和设备id到检验与设备关系表中查询是否已存在记录，只写入不存在的数据
            Integer integer = mapper.queryCountRelation(calibrationView.getId(), deviceCalibration.getId());
            if (integer <= 0) {
                DeviceCalibrationRelation relation = new DeviceCalibrationRelation();
                relation.setDeviceCalibrationId(deviceCalibration.getId());
                relation.setDeviceId(calibrationView.getId());
                mapper.insertRelation(relation);
            }
        }
    }

    @Override
    public Integer saveCalibrationRelation(DeviceCalibrationRelation relation) {
        if (relation == null) {
            return BusinessCode.SUCCESS.getCode();
        }
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            DeviceCalibrationMapper mapper = factory.getMapper(DeviceCalibrationMapper.class);
            DeviceCalibration deviceCalibration = mapper.queryOne(relation.getDeviceCalibrationId());
            if (deviceCalibration == null) {
                factory.close(false);
                return BusinessCode.EXCEPTION.getCode();
            } else if (deviceCalibration.getStatus() != STATUS_0) {
                factory.close(false);
                return BusinessCode.EXCEPTION.getCode();
            }
            DeviceCalibrationRelation other = mapper.queryRelation(relation.getDeviceCalibrationId(), relation.getDeviceId());
            if (other != null) {
                mapper.updateRelation(relation);
            } else {
                mapper.batchInsertRelation(new ArrayList() {{
                    add(relation);
                }});
            }
            // 修改 设置台账 记录的检查日期
            if (factory.getMapper(DeviceMapper.class).updateLastCaliDateById(relation.getDeviceId(), relation.getCalibrationDate()) != 1) {
                factory.close(false);
                return BusinessCode.EXCEPTION.getCode();
            }
            factory.close(true);
            return BusinessCode.SUCCESS.getCode();
        } catch (Exception e) {
            if (factory != null) {
                factory.close(false);
            }
            return BusinessCode.EXCEPTION.getCode();
        }
    }

    @Override
    public DataBean<CalibrationView> fetchDeviceInCalibration(String corpCode, String responsibleEmployeeCode, String deviceCalibrationId, Integer start, Integer rows) {
        DataBean<CalibrationView> dataBean = new DataBean<>();
        List<CalibrationView> views = null;
        Integer total = 0;
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCalibration calibration = factory.getMapper(DeviceCalibrationMapper.class).queryOne(deviceCalibrationId);
            if (calibration == null) {
                views = Collections.EMPTY_LIST;
            } else {
                //根据水司code,检查人code和检验记录id查询设备信息列表
                views = factory.getMapper(DeviceMapper.class).queryResponsibleEmployee(corpCode, responsibleEmployeeCode, deviceCalibrationId, start, rows);
                //views = factory.getMapper(DeviceMapper.class).queryDeviceInCalibration(responsibleEmployeeCode, null, start, rows);
                /*for (CalibrationView view : views) {
                    view.setDescription(null);
                    view.setCalibrationDate(null);
                    view.setNormal(null);
                    view.setValidationDate(null);
                    view.setResult(null);
                }*/
                //根据水司code，检查人code和检验记录id查询设备信息总条数
                total = factory.getMapper(DeviceMapper.class).countResponsibleEmployee(corpCode, responsibleEmployeeCode, deviceCalibrationId);
                //total = factory.getMapper(DeviceMapper.class).countDeviceInCalibration(responsibleEmployeeCode, null);
                //查询检查责任人的设备检查结果(即是否正常)
                List<CalibrationView> resultViews = factory.getMapper(DeviceMapper.class).queryDeviceInCalibration(responsibleEmployeeCode, deviceCalibrationId, null, null);
                if (!resultViews.isEmpty()) {
                    for (CalibrationView resultView : resultViews) {
                        views.stream().forEach(v -> {
                            if (v.getId().equals(resultView.getId())) {
                                v.setNormal(resultView.getNormal());
                                v.setDescription(resultView.getDescription());
                                v.setCalibrationDate(resultView.getCalibrationDate());
                                v.setValidationDate(resultView.getValidationDate());
                                v.setResult(resultView.getResult());
                                v.setDeviceTypeId(resultView.getDeviceTypeId());
                                v.setDeviceTypeName(resultView.getDeviceTypeName());
                            }
                        });
                    }
                }
            }
            dataBean.setList(views);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(total);
            if (rows != null) {
                dataBean.setTotalPage(total > rows ? (total % rows == 0 ? total / rows : total / rows + 1) : 1);
                dataBean.setPageNo(start / rows + 1);
            }
            return dataBean;
        }
    }

    @Override
    public DataBean<CalibrationView> fetchAllDeviceInCalibration(String corpCode, String responsibleEmployeeCode, String deviceCalibrationId, String deviceIds, Integer start, Integer rows) {
        DataBean<CalibrationView> dataBean = new DataBean<>();
        List<String> deviceIdList = JSONObject.parseArray(deviceIds, String.class);
        List<CalibrationView> calibrationViews = new ArrayList<>();
        Integer total = 0;
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCalibration calibration = factory.getMapper(DeviceCalibrationMapper.class).queryOne(deviceCalibrationId);
            if (calibration == null) {
                calibrationViews = Collections.EMPTY_LIST;
            } else {
                List<CalibrationView> views = factory.getMapper(DeviceMapper.class).queryForResponsibleEmployee(corpCode, responsibleEmployeeCode, start, rows);
                for (CalibrationView calibrationView : views) {
                    boolean contains = deviceIdList.contains(calibrationView.getId());
                    if (!contains) {
                        calibrationViews.add(calibrationView);
                    }
                }
                total = calibrationViews.size();
            }
        }
        dataBean.setList(calibrationViews);
        dataBean.setPageSize(rows);
        dataBean.setTotalNumber(total);
        if (rows != null) {
            dataBean.setTotalPage(total > rows ? (total % rows == 0 ? total / rows : total / rows + 1) : 1);
            dataBean.setPageNo(start / rows + 1);
        }
        return dataBean;
    }


    @Override
    public Boolean uploadCalibrationAttachment(String deviceCalibrationId, String delFileAddress, String keepFileAddress, MultipartFile[] files) {
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCalibration deviceCalibration = factory.getMapper(DeviceCalibrationMapper.class).queryOne(deviceCalibrationId);
            if (deviceCalibration == null) {
                return false;
            } else if (deviceCalibration.getStatus() != STATUS_0) {
                return false;
            }
            List<String> fileList = null;
            List<String> previewList = null;
            if (StringUtils.isNotEmpty(deviceCalibration.getAttachment())) {
                fileList = JSONObject.parseArray(deviceCalibration.getAttachment(), String.class);
            }
            if (StringUtils.isNotEmpty(deviceCalibration.getPreviewAttachment())) {
                previewList = JSONObject.parseArray(deviceCalibration.getPreviewAttachment(), String.class);
            }
            List<String> newAtts = new ArrayList<>();
            List<String> previewAtts = new ArrayList<>();
            if (files != null && files.length > 0) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    newAtts.add(url + "#" + file.getOriginalFilename());
                    String previewUrl = docConverterUtils.converterUpdate(file);
                    if (StringUtils.isNotBlank(previewUrl)) {
                        previewAtts.add(previewUrl);
                    } else {
                        previewAtts.add(url);
                    }
                }
            }

            if (StringUtils.isNotEmpty(delFileAddress)) {
                String[] delAttsArray = delFileAddress.split("[;；]");
                for (String att : delAttsArray) {
                    clientWrapper.deleteFile(att.split("#")[0]);
                    if (null != fileList && null != previewList) {
                        for (int i = 0; i < fileList.size(); i++) {
                            if (fileList.get(i).equalsIgnoreCase(att)) {
                                clientWrapper.deleteFile(previewList.get(i));
                            }
                        }
                    }
                }
            }

            if (StringUtils.isNotEmpty(keepFileAddress)) {
                String[] keepAttsArray = keepFileAddress.split("[;；]");
                newAtts.addAll(Arrays.asList(keepAttsArray));
                for (String att : keepAttsArray) {
                    if (null != fileList && null != previewList) {
                        for (int i = 0; i < fileList.size(); i++) {
                            if (fileList.get(i).equalsIgnoreCase(att)) {
                                previewAtts.add(previewList.get(i));
                            }
                        }
                    }
                }
            }
            String attachment = newAtts.isEmpty() ? "" : new Gson().toJson(newAtts);
            String previewAttachment = newAtts.isEmpty() ? "" : new Gson().toJson(previewAtts);
            return factory.getMapper(DeviceCalibrationMapper.class).updateCalibrationAttachment(deviceCalibrationId, attachment, previewAttachment) > 0;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return false;
        }
    }

    @Override
    public List<String> getCalibrationAttachment(String deviceCalibrationId) {
        try (SessionFactory factory = new SessionFactory()) {
            String ids = factory.getMapper(DeviceCalibrationMapper.class).queryCalibrationAttachment(deviceCalibrationId);
            if (StringUtils.isNotBlank(ids)) {
                return JSONObject.parseArray(ids, String.class);
            }
            return null;
        }
    }


    @Override
    public MessageBean submit(StaffBean user, DeviceCalibration deviceCalibration) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        SessionFactory factory = new SessionFactory();
        try {
            deviceCalibration.setStatus(STATUS_1);
            deviceCalibration.setUpdateUser(user.getCode());
            deviceCalibration.setUpdateTime(new Date());
            deviceCalibration.setUpdateUserName(user.getName());
            if (factory.getMapper(DeviceCalibrationMapper.class).update(deviceCalibration) == 1) {
                // 启动流程
                if (StringUtils.isEmpty(deviceCalibration.getResponsibleEmployeeCode())) {
                    factory.close(false);
                    msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                    msg.setDescription("设备负责人不能为空");
                    return msg;
                }
                Audit audit = new Audit("设备检验结果确认", "检验记录审批", user.getName(), new Date());
                audit.setTitle("设备检验结果确认");
                audit.setDescription("检验记录审批");
                audit.setCorpCode(deviceCalibration.getCorpCode());
                audit.setCorpName(deviceCalibration.getCorpName());

                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setInitiatorCode(user.getCode());
                audit.setTarget(this.getClass().getName());
                audit.setSetCode(setCode);
                audit.setTemplateKey(templateKey);
                audit.setOperation(1);
                audit.setState(1);
                audit.setFlowType(1);
                audit.setFlowName("设备检验结果确认");
                List<String> idList = Arrays.asList(deviceCalibration.getId());
                audit.setBusinessIds(new Gson().toJson(idList));
                Map map = new HashMap();
                String managerUserid = "";
                List<StaffBean> staffBeans = (List<StaffBean>) util.staff(deviceCalibration.getResponsibleEmployeeCode().split("_")[0], null).getData();
                managerUserid = staffBeans.get(0).getUserid();
                map.put("manager", managerUserid);
                if (!flowManagement.initFlow(user, audit, map)) {
                    factory.close(false);
                    msg.setCode(com.koron.hazardsource.util.BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
                    msg.setDescription(com.koron.hazardsource.util.BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
                    return msg;
                }
                factory.close();
                return msg;
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setData(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setData(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    /**
     * 根据水司code和检验记录id删除检验明细
     *
     * @param corpCode
     * @param deviceCalibrationId
     * @return
     */
    @Override
    public MessageBean<Integer> deleteCalibrationRelation(String corpCode, String deviceCalibrationId, String deviceId) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            Integer integer = factory.getMapper(DeviceMapper.class).queryCalibrationRelation(corpCode, deviceCalibrationId);
            if (integer <= 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("不存在的检查明细");
            } else {
                Integer deleteDevice = factory.getMapper(DeviceMapper.class).deleteCalibrationRelation(deviceCalibrationId, deviceId);
                if (deleteDevice > 0) {
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription(BusinessCode.SUCCESS.getDescription());
                }
            }
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 添加检查明细信息
     *
     * @param corpCode            水司code
     * @param deviceCalibrationId 检验记录id
     * @param deviceIds           设备id集合
     * @return
     */
    @Override
    public MessageBean<Integer> addCalibrationRelation(String corpCode, String deviceCalibrationId, String deviceIds) {
        MessageBean<Integer> msg = new MessageBean<>();
        List<String> deviceIdList = JSONObject.parseArray(deviceIds, String.class);
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCalibrationMapper mapper = factory.getMapper(DeviceCalibrationMapper.class);
            for (int i = 0; i < deviceIdList.size(); i++) {
                DeviceCalibrationRelation relation = new DeviceCalibrationRelation();
                relation.setDeviceCalibrationId(deviceCalibrationId);
                relation.setDeviceId(deviceIdList.get(i));
                Integer integer = mapper.insertRelation(relation);
                if (integer > 0) {
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription(BusinessCode.SUCCESS.getDescription());
                } else {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("第" + (i + 1) + "个检查设备添加失败");
                    return msg;
                }
            }
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public List<DeviceCalibration> exportList(String corpCode, String title, String responsibleEmployeeName, String calibrationCorp, Integer status) {
        try (SessionFactory factory = new SessionFactory()) {
            String codes = util.getCodes(corpCode);
            List<DeviceCalibration> deviceCalibrations = factory.getMapper(DeviceCalibrationMapper.class).queryByCondition(codes, title, responsibleEmployeeName, calibrationCorp, status, null, null,null);
            if (null != deviceCalibrations && deviceCalibrations.size() > 0) {
                deviceCalibrations.forEach(dc -> {
                    CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(dc.getCorpCode());
                    if (corpBean != null) {
                        dc.setCorpName(corpBean.getCorpName());
                    }
                });
            }
            return deviceCalibrations;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public CalibrationView fetchOneDeviceInCalibration(String corpCode, String responsibleEmployeeCode, String deviceCalibrationId, String deviceId) {
        CalibrationView view = null;
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCalibration calibration = factory.getMapper(DeviceCalibrationMapper.class).queryOne(deviceCalibrationId);
            if (null != calibration) {
                //根据水司code,检查人code和检验记录id查询设备信息列表
                view = factory.getMapper(DeviceMapper.class).queryOneResponsibleEmployee(corpCode, responsibleEmployeeCode, deviceCalibrationId, deviceId);
                if (null != view) {
                    //查询检查责任人的设备检查结果(即是否正常)
                    List<CalibrationView> resultViews = factory.getMapper(DeviceMapper.class).queryOneDeviceInCalibration(responsibleEmployeeCode, deviceCalibrationId, deviceId);
                    if (!resultViews.isEmpty()) {
                        for (CalibrationView resultView : resultViews) {
                            if (view.getId().equals(resultView.getId())) {
                                view.setNormal(resultView.getNormal());
                                view.setDescription(resultView.getDescription());
                                view.setCalibrationDate(resultView.getCalibrationDate());
                                view.setValidationDate(resultView.getValidationDate());
                                view.setResult(resultView.getResult());
                                view.setDeviceTypeId(resultView.getDeviceTypeId());
                                view.setDeviceTypeName(resultView.getDeviceTypeName());
                            }
                        }
                    }
                }
            }
            return view;
        }
    }

    @Override
    public void editApproval(Audit audit) {
        Optional.ofNullable(audit)
                .map(obj -> obj.getBusinessIds())
                .map(ids -> {
                    List<String> list = JSON.parseArray(ids, String.class);
                    return Optional.ofNullable(list);
                }).map(idsList -> {
            List<String> idList = idsList.get();
            Optional.ofNullable(idList).map(ids -> {
                SessionFactory factory = new SessionFactory();
                try {
                    DeviceCalibrationMapper mapper = factory.getMapper(DeviceCalibrationMapper.class);
                    for (String id : ids) {
                        // 状态(0-草稿 1-审批中 2-已审批)
                        if (mapper.updateStatus(id, STATUS_2) != 1) {
                            factory.close(false);
                            return null;
                        }
                    }
                    factory.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                    factory.close(false);
                }
                return null;
            });
            return null;
        });
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {
        Optional.ofNullable(audit)
                .map(obj -> obj.getBusinessIds())
                .map(ids -> {
                    List<String> list = JSON.parseArray(ids, String.class);
                    return Optional.ofNullable(list);
                }).map(idsList -> {
            List<String> idList = idsList.get();
            Optional.ofNullable(idList).map(ids -> {
                SessionFactory factory = new SessionFactory();
                try {
                    DeviceCalibrationMapper mapper = factory.getMapper(DeviceCalibrationMapper.class);
                    for (String id : ids) {
                        // 状态(0-草稿 1-审批中 2-已审批)
                        if (mapper.updateStatus(id, STATUS_0) != 1) {
                            factory.close(false);
                            return null;
                        }
                    }
                    factory.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                    factory.close(false);
                }
                return null;
            });
            return null;
        });
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        flowManagement.getHandlers().put(this.getClass().getName(), new DeviceCalibrationServiceImpl());
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
